import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Delayed;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;


public class SYTEventManager {
	private LinkedBlockingQueue<SYTEvent> sytEventList;
	private Map<String, SYTEventHandler> eventHandlers;
	private ThreadPoolTaskExecutor taskExecutor;

	
	public SYTEventManager(){
		sytEventList = new LinkedBlockingQueue<SYTEvent>();
		eventHandlers = Collections.synchronizedMap(new HashMap<String, SYTEventHandler>());
	}
	
	public void initThread(){
		new Thread(new SYTEventManagerRunnable()).start();
	}
	
	public void addEvent(SYTEvent sytEvent,SYTEventHandler sytEventHandler){
		SYTEventHandler oldHandler = eventHandlers.get(sytEvent.getId());
		if(oldHandler == null){
			eventHandlers.put(sytEvent.getId(), sytEventHandler);
		}else{
			oldHandler.setNext(sytEventHandler);
		}
	}
	
	public void dispatchEvent(SYTEvent sytEvent){
		sytEventList.offer(sytEvent);
	}
	
	public void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
		this.taskExecutor = taskExecutor;
	}


	public void doEventHandler(SYTEvent sytEvent){
		SYTEventHandler sytEventHandler = eventHandlers.get(sytEvent.getId());
		taskExecutor.execute(sytEventHandler);
	}
	
	class SYTEventManagerRunnable implements Runnable {
			
		public void run() {
			while (!Thread.interrupted()) {
				try {
					SYTEvent sytEvent = sytEventList.take();
					doEventHandler(sytEvent);
				} catch (InterruptedException e) {
					
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		
		
	}
	
}

